﻿using System.Collections.Generic;
using FluentParser.Utils;

namespace FluentParser.Tests.Grammars
{
    public class DictionaryGrammar : Grammar<Dictionary<string, string>>
    {
        public DictionaryGrammar()
        {
            var parseValue = ParseString.Regex("[^,]+");
            var parsePair = parseValue + "," + parseValue;
            var parsePairCollection = parsePair.Repeat(0, "\n");
            var parseDictionary = parsePairCollection.Convert(x => BuildDictionary(x));

            Root = parseDictionary;
        }

        private static Dictionary<string, string> BuildDictionary(Tuple<string, string>[] pairs)
        {
            var dict = new Dictionary<string, string>();
            foreach (Tuple<string, string> pair in pairs)
                dict.Add(pair.Item1, pair.Item2);

            return dict;
        }
    }
}